package com.stars.pao.aicloud.controller;

import com.baidubce.qianfan.Qianfan;
import com.baidubce.qianfan.model.chat.ChatResponse;
import com.baidubce.qianfan.model.image.Text2ImageResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.stars.pao.aicloud.entity.Answer;
import com.stars.pao.aicloud.entity.enums.AiModelEnum;
import com.stars.pao.aicloud.entity.enums.AiTypeEnum;
import com.stars.pao.aicloud.service.IAnswerService;
import com.stars.pao.aicloud.util.AppVariable;
import com.stars.pao.aicloud.util.MinIoUtil;
import com.stars.pao.aicloud.util.ResponseEntity;
import com.stars.pao.aicloud.util.SecurityUtil;
import com.stars.pao.aicloud.util.idempotent.Idempotent;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 百度大模型（千帆）操作
 * 接口调用有限制
 */

@Tag(name = "千帆大模型控制器")
@RequestMapping("/qianfan")
@RestController
public class QianfanController {

    @Value("${qianfan.api-key}")
    private String apiKey;
    @Value("${qianfan.api-secret}")
    private String secretKey;
    @Resource
    private IAnswerService answerService;
    @Resource
    private MinIoUtil minIoUtil;
    @Resource
    private RedissonClient redissonClient;

    /**
     * 聊天
     */
    @Idempotent
    @PostMapping("/chat")
    public ResponseEntity chat(String question) {
        if (!StringUtils.hasLength(question)) {
            // 输入为空
            return ResponseEntity.fail("请先输入内容！");
        }
        // 执行分布式锁
        Long uid = SecurityUtil.getCurrentUser().getUid();
        String lockKey = AppVariable.getModelLockKey(uid,
                AiModelEnum.QIANFAN.getValue(),
                AiTypeEnum.CHAT.getValue());
        String result = ""; // 大模型返回的结构
        boolean isSave = false; // 数据添加状态
        // 获取分布式锁实例
        RLock rLock = redissonClient.getLock(lockKey);
        try {
            boolean isLock = rLock.tryLock(30, TimeUnit.SECONDS);
            if (!isLock) {
                // 获取分布式锁失败
                return ResponseEntity.fail("请勿频繁请求，请稍后再试");
            }
            ChatResponse response = new Qianfan(apiKey, secretKey).chatCompletion()
                    .model("ERNIE-Speed-8K") // 使用model指定预置模型
                    // .endpoint("completions_pro") // 也可以使用endpoint指定任意模型 (二选一)
                    .addMessage("user", question) // 添加用户消息 (此方法可以调用多次，以实现多轮对话的消息传递)
                    .execute(); // 发起请求
            String content = response.getResult();

            Answer answer = new Answer();
            answer.setTitle(question);
            answer.setContent(content);
            answer.setModel(AiModelEnum.QIANFAN.getValue());
            answer.setUid(uid);
            answer.setType(AiTypeEnum.CHAT.getValue());
            isSave = answerService.save(answer);
        } catch (Exception e) {
        } finally {
            rLock.unlock();
        }
        if (!isSave) {
            return ResponseEntity.fail("数据保存失败，请重试");

        }
        return ResponseEntity.succ(isSave);
    }


    // 历史聊天展示
    @PostMapping("/getChatList")
    public ResponseEntity getChatList() {
        QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", SecurityUtil.getCurrentUser().getUid());
        queryWrapper.eq("model", AiModelEnum.QIANFAN.getValue());
        queryWrapper.eq("type", AiTypeEnum.CHAT.getValue());
        queryWrapper.orderByDesc("aid");
        List<Answer> list = answerService.list(queryWrapper);
        return ResponseEntity.succ(list);
    }

    @Idempotent
    // 绘图功能
    @PostMapping("/draw")
    public ResponseEntity draw(String question) {
        if (!StringUtils.hasLength(question)) {
            // 输入为空
            return ResponseEntity.fail("请先输入内容！");
        }
        // 执行分布式锁
        Long uid = SecurityUtil.getCurrentUser().getUid();
        String lockKey = AppVariable.getModelLockKey(uid,
                AiModelEnum.QIANFAN.getValue(),
                AiTypeEnum.DRAW.getValue());
        String url = ""; // 大模型返回的结构
        boolean isSave = false; // 数据添加状态
        // 获取分布式锁实例
        RLock rLock = redissonClient.getLock(lockKey);
        try {
            boolean isLock = rLock.tryLock(30, TimeUnit.SECONDS);
            if (!isLock) {
                // 获取分布式锁失败
                return ResponseEntity.fail("请勿频繁请求，请稍后再试");
            }
            Text2ImageResponse response = new Qianfan(apiKey, secretKey)
                    .text2Image()
                    .prompt(question)
                    .execute();
            byte[] image = response.getData().get(0).getImage();
            String fileName = "qf-" + UUID.randomUUID().toString().replace("-", "");
            try (ByteArrayInputStream inputStream = new ByteArrayInputStream(image)) {
                url = minIoUtil.upload(fileName, inputStream, "image/png");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            Answer answer = new Answer();
            answer.setTitle(question);
            answer.setContent(url);
            answer.setModel(AiModelEnum.QIANFAN.getValue());
            answer.setType(AiTypeEnum.DRAW.getValue());
            answer.setUid(uid);
            isSave = answerService.save(answer);
        } catch (Exception e) {
        } finally {
            rLock.unlock();
        }
        if (isSave) {
            return ResponseEntity.succ(url);
        }
        return ResponseEntity.fail("数据保存失败，请重试");
    }

    // 历史绘图展示
    @PostMapping("/getDrawList")
    public ResponseEntity getDrawList() {
        QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", SecurityUtil.getCurrentUser().getUid());
        queryWrapper.eq("model", AiModelEnum.QIANFAN.getValue());
        queryWrapper.eq("type", AiTypeEnum.DRAW.getValue());
        queryWrapper.orderByDesc("aid");
        List<Answer> list =answerService.list(queryWrapper);
        return ResponseEntity.succ(list);
    }
}